import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:http_parser/http_parser.dart';
import 'package:tender_flutter/constant/api_path.dart';
import 'package:tender_flutter/generated/json/base/json_convert_content.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/http/http_utils.dart';
import 'package:tender_flutter/page/common/model/upload_result_entity.dart';
import 'package:tender_flutter/page/home/model/city_entity.dart';

class ApiCommon {
  /// 全局城市数据
  static List<CityEntity> cityDatas = null;

  /// 获取城市列表
  static Future<List<CityEntity>> getCityDatas() async {
    if (cityDatas != null) {
      return cityDatas;
    }
    var value = await rootBundle.loadString('assets/json/cities2.json');
    var response = json.decode(value.toString());
    List<CityEntity> datas = JsonConvert.fromJsonAsT(response);
    print(datas);
    for (int i = 0; i < datas.length; i++) {
      CityEntity province = datas[i];

      Map<String, dynamic> proMap = province.toJson();
      proMap["areas"] = [];
      CityEntity all = JsonConvert.fromJsonAsT<CityEntity>(proMap);
      all.title = "全部";
      province.areas.insert(0, all);

      for (int j = 0; j < province.areas.length; j++) {
        CityEntity cityEntity = province.areas[j];

        Map<String, dynamic> cityMap = cityEntity.toJson();
        cityMap["areas"] = [];
        CityEntity cAll = JsonConvert.fromJsonAsT<CityEntity>(cityMap);
        all.title = "全部";
        province.areas[j].areas.insert(0, cAll);
      }
    }

    cityDatas = datas;
    return datas;
  }

  /// 根据省市名称和城市code获取需要的具体城市信息（主要是为了获取城市ID）
  static Future<ApiResponse<CityEntity>> getCityByCodeOrName(
      {@required String title, @required String code}) async {
    try {
      Map<String, dynamic> params = HashMap();
      params["code"] = code;
      params["title"] = title;
      final response =
          await HttpUtils.postForm(ApiPath.cityInfo, params: params);
      return ApiResponse<CityEntity>.completed(response);
    } on DioError catch (e) {
      return ApiResponse.error(e.error);
    }
  }

  /// 上传图片
  /// file  图片文件
  static Future<ApiResponse<UploadResultEntity>> uploadImage(
      List<File> imageFiles) async {
    try {
      Map<String, dynamic> params = HashMap();
      // FormData formData = FormData();
      // for (File file in imageFiles) {
      //   formData.files.add(MapEntry(
      //       "image",
      //       MultipartFile.fromBytes(
      //         file.readAsBytesSync(),
      //         filename: '${DateTime.now().millisecondsSinceEpoch}.jpeg',
      //       )));
      // }
      // params["image"] = MultipartFile.fromBytes(imageFiles[0].readAsBytesSync(),
      //     filename: '${DateTime.now().millisecondsSinceEpoch}.jpg');

      String path = imageFiles[0].path;
      var name = path.substring(path.lastIndexOf("/") + 1, path.length);
      String imageType = name.substring(name.lastIndexOf(".") + 1, name.length);
      params["image"] = await MultipartFile.fromFile(path,
          filename: name, contentType: MediaType.parse("image/$imageType"));
      final response =
          await HttpUtils.postForm(ApiPath.uploadImage, params: params);
      return ApiResponse<UploadResultEntity>.completed(response);
    } on DioError catch (e) {
      return ApiResponse.error(e.error);
    }
  }

  /// 注册极光registonId
  static Future<ApiResponse> registerRegId({@required String regId}) async {
    try {
      Map<String, dynamic> params = HashMap();
      params["reg_id"] = regId;
      final response =
          await HttpUtils.get(ApiPath.register_regid, params: params);
      return ApiResponse.completed(response);
    } on DioError catch (e) {
      return ApiResponse.error(e.error);
    }
  }
}
